package com.tcs.service;

import javax.annotation.Resource;

import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.tcs.job.RequestJob;
import com.tcs.model.porxypool.RequestParamsBean;
import com.tcs.model.porxypool.proxyPoolBean;
import com.tcs.quartz.PorxyPoolScheduler;
import com.tcs.util.constant.SystemConstants;
import com.tcs.util.staticpack.StaticPack;

/**
 * 代理池逻辑模型
 * @author wangbo
 */
@Service("proxyService")
public class ProxyService implements IProxyService {
	
	private final Logger logger = LoggerFactory.getLogger(ProxyService.class);
	
	@Resource(name="porxyPoolScheduler")
	private PorxyPoolScheduler porxyPoolScheduler;
	
	@Resource(name="staticPack")
	private StaticPack<String, proxyPoolBean> staticPack;
	
	private JobDataMap jobDataMap = null;
	private JobDetail jobDetail = null;
	private Trigger trigger = null;
	private Scheduler scheduler = null;
	private Integer index = 0;

	@Override
	public void work() throws SchedulerException {
		scheduler = porxyPoolScheduler.getScheduler();
		proxyPoolBean proxyPoolBean = staticPack.get(SystemConstants.ProxyPool.PROXYPOOLMODEL);
		logger.info("ProxyPoolBean : {} " , proxyPoolBean);
		for (RequestParamsBean requestParamsBean : proxyPoolBean.getRequestConfig()) {
			jobDataMap = new JobDataMap();
			jobDataMap.put(SystemConstants.ProxyPool.REQUESTPARAMSBEAN , requestParamsBean);
			jobDataMap.put(SystemConstants.ProxyPool.PROXYPOOLMODEL , proxyPoolBean);
			jobDetail = JobBuilder.newJob(RequestJob.class)
					.setJobData(jobDataMap)
	                .withDescription(requestParamsBean.toString())
	                .withIdentity(requestParamsBean.getJobName(), requestParamsBean.getJobGroup())
	                .build();
			trigger = TriggerBuilder.newTrigger()
                    .withDescription(requestParamsBean.toString())
                    .withIdentity("trigger" + ++index, "triggerGroup" + index)
                    .withSchedule(CronScheduleBuilder.cronSchedule(requestParamsBean.getCron()))
                    .startNow()
                    .build();
			scheduler.scheduleJob(jobDetail, trigger);
		}
		scheduler.start();
	}
}